package world.zwq.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import world.zwq.common.constant.ProductConstant;
import world.zwq.common.to.SkuHasStockVo;
import world.zwq.common.to.SkuReductionTo;
import world.zwq.common.to.SpuBoundTo;
import world.zwq.common.to.es.SkuEsModel;
import world.zwq.common.utils.PageUtils;
import world.zwq.common.utils.Query;

import world.zwq.common.utils.R;
import world.zwq.gulimall.product.dao.SpuInfoDao;
import world.zwq.gulimall.product.entity.*;
import world.zwq.gulimall.product.feign.CouponFeignService;
import world.zwq.gulimall.product.feign.SearchFeignService;
import world.zwq.gulimall.product.feign.WareFeignService;
import world.zwq.gulimall.product.service.*;
import world.zwq.gulimall.product.vo.*;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService attrValueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * TODO 高级部分完善异常措施
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息：pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);
        //2、保存spu的描述图片：pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);
        //3、保存spu图片集：pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(infoEntity.getId(),images);
        //4、保存spu规格参数：pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            AttrEntity id = attrService.getById(attr.getAttrId());
            attrValueEntity.setSpuId(infoEntity.getId());
            attrValueEntity.setAttrId(attr.getAttrId());
            attrValueEntity.setAttrValue(attr.getAttrValues());
            attrValueEntity.setAttrName(id.getAttrName());
            attrValueEntity.setQuickShow(attr.getShowDesc());
            return attrValueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveBatch(collect);
        //5、保存spu积分信息：gulimall_sms->sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r.getCode() != 0){
            log.error("远程保存积分信息失败");
        }
        //5、保存当前spu对应sku销售属性信息：
        //5.1 基本信息pms_sku_info
        List<Skus> skus = vo.getSkus();
        skus.forEach(item->{
            String defaultImg = "";
            for (Images img : item.getImages()) {
                if(1==img.getDefaultImg()){
                    defaultImg = img.getImgUrl();
                }
            }
            //    private String skuName;
            //    private BigDecimal price;
            //    private String skuTitle;
            //    private String skuSubtitle;
            SkuInfoEntity sku = new SkuInfoEntity();
            BeanUtils.copyProperties(item,sku);
            sku.setBrandId(infoEntity.getBrandId());
            sku.setCatalogId(infoEntity.getCatalogId());
            sku.setSaleCount(0L);
            sku.setSpuId(infoEntity.getId());
            sku.setSkuDefaultImg(defaultImg);
            skuInfoService.saveSkuInfo(sku);
            Long skuId = sku.getSkuId();
            List<SkuImagesEntity> imagesEntities = item.getImages().stream()
                    .filter(img-> StringUtils.isNotBlank(img.getImgUrl()))
                    .map(img -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setDefaultImg(img.getDefaultImg());
                skuImagesEntity.setImgUrl(img.getImgUrl());
                return skuImagesEntity;
            }).collect(Collectors.toList());
            //5.2 sku图片信息 pms_sku_images
            //TODO 没有图片路径的无需保存
            skuImagesService.saveBatch(imagesEntities);
            //5.3 sku 销售属性信息 pms_sku_sale_attr_value
            List<Attr> attrs = item.getAttr();
            List<SkuSaleAttrValueEntity> saleAttrValueEntities = attrs.stream().map(attr -> {
                SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, attrValueEntity);
                attrValueEntity.setSkuId(skuId);
                return attrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(saleAttrValueEntities);
            //5.4 sku 优惠、满减等信息 gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(item,skuReductionTo);
            skuReductionTo.setSkuId(skuId);
            if(skuReductionTo.getFullCount()> 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0)) == 1){
                R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                if(r1.getCode() != 0){
                    log.error("远程保存优惠满减信息失败");
                }

            }
        });

    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)){
            wrapper.and(wrapper1-> wrapper1.eq("id",key).or().like("spu_name",key));
        }
        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotBlank(brandId) && !"0".equals(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if(StringUtils.isNotBlank(catelogId) && !"0".equals(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        String status = (String) params.get("status");
        if(StringUtils.isNotBlank(status)){
            wrapper.eq("publish_status",status);
        }
        /*
         * status:
            key:
            brandId: 0
            catelogId: 0
         */
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //组装需要的数据
        //1、查询出当前spuId对应的所有的sku信息，品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        //4、查询当前spu所有的可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> searchIds = attrService.selectSearchAttrs(attrIds);
        Set<Long> idSet = new HashSet<>(searchIds);
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> idSet.contains(item.getAttrId())).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());
        //1、发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> skuStockMap = null;
        try {
            List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
            R r = wareFeignService.getSkusHasStock(skuIds);
            TypeReference<List<SkuHasStockVo>> tTypeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            skuStockMap = r.getData(tTypeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock, (oldV, newV) -> newV));
        } catch (Exception e) {
            log.error("库存服务查询异常",e);
        }
        Map<Long, Boolean> finalStockMap = skuStockMap;
        //2、封装每个sku信息
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,esModel);
            //price,skuImg,
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            // hasStock,hotScore,
            esModel.setHasStock(finalStockMap == null ? true : finalStockMap.get(sku.getSkuId()));

            //TODO 2、热度评分。 0
            esModel.setHotScore(0L);
            //3、查询品牌和分类的名字信息
            // brandName,brandImg,catalogName
            BrandEntity brand = brandService.getById(sku.getBrandId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());
            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            esModel.setCatalogName(category.getName());

            //attrs检索属性
            esModel.setAttrs(attrsList);

            return esModel;
        }).collect(Collectors.toList());
        //TODO 5、将数据发送给es进行保存gulimapp-search
         R r = searchFeignService.productStatusUp(upProducts);
        if(r.getCode() == 0){
            //商品上架成功
            //修改当前spu上架状态
            try {
                this.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
            } catch (Exception e) {
                log.error("一场",e);
            }
        }else {
            //远程调用失败
            //TODO 7、重复调用？接口幂等性；重试机制
        }

    }


}